package com.yonyou.crm.sact.visit.ctrl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.sact.visit.entity.VisitsVO;
import com.yonyou.crm.sact.visit.rmitf.IVisitsRmService;


@RestController
@RequestMapping(value = "/{version}/sact/visits")
public class VisitCtrl {

	@Autowired
	private IVisitsRmService service;
	
	/**
	 * 查询拜访计划
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object list(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);

		@SuppressWarnings("unchecked")
		Page<VisitsVO> visitPage = service.getList(getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));
		
		return ResponseUtil.getObject(visitPage);
	}
	
	private Page<VisitsVO> getRequestPage(JSONObject paramObj) throws CrmMessageException {
		
		Integer page = paramObj.getInt(HttpKeyConstant.Page);
		Integer pageSize = paramObj.getInt(HttpKeyConstant.PageSize);
		
		if (page == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "page不能为空");
		}
		
		if (pageSize == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "pageSize不能为空");
		}
		
		return new Page<VisitsVO>(page, pageSize);
	}

	/**
	 * 拜访计划详情
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "id不能为空");
		}		
		
		return ResponseUtil.getObject(service.getDetail(id));
	}
	
	
	/**
	 * 新增拜访计划
	 * @param request
	 * @param response
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(method = RequestMethod.POST)
	public Object insert(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException, ParseException {

		JSONObject paramObj = RequestUtil.getParamObject(request);
		
		String dateStr = paramObj.getString("date");
		Date date = transfromDateFromStr(dateStr);
		
		VisitsVO visit = RequestUtil.getVO(request, VisitsVO.class);
		String validMsg = checkVOVaidator(visit);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}
		
		visit.setDate(date);

		validMsg = insertValidator(visit);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}
		
		visit = service.insert(visit);
		
		if (visit.getId() == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "获取自增主键为空");
		}
				
		return ResponseUtil.getObject(visit);
	}
	
	private String checkVOVaidator(VisitsVO visit){
		if (visit == null) {
			return "转换实体失败";
		}
		return "";
	}

	private String insertValidator(VisitsVO visit) {
		
		if (visit.getDate() == null) {
        	return  "拜访日期不能为空";
		}
		
		if (visit.getCumId() == null) {
        	return "客户不能为空";
		}
		
		if (StringUtils.isBlank(visit.getPurpose())) {
        	return "拜访目的不能为空";
		}
		
		return "";
	}
	
	/**
	 * 修改拜访计划
	 * @param request
	 * @param response
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.PUT)
	public Object update(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException, ParseException {

		JSONObject paramObj = RequestUtil.getParamObject(request);
		String dateStr = paramObj.getString("date");
		Date date = transfromDateFromStr(dateStr);
		
		VisitsVO visit = RequestUtil.getVO(request, VisitsVO.class);
		String validMsg = checkVOVaidator(visit);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}
		
		visit.setId(id);
		visit.setDate(date);

		validMsg = updateValidator(visit);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}

		VisitsVO newVisit = service.update(visit);
		
		return ResponseUtil.getObject(newVisit);
	}
	
	private String updateValidator(VisitsVO visit) {
		
		if ((visit.getId() == null) || (visit.getId() == 0)) {
        	return "客户不存在";
		}
		
		if (visit.getCumId() == null) {
        	return "客户不能为空";
		}
		
		if (visit.getDate() == null) {
        	return "拜访日期不能为空";
		}
		
		if (StringUtils.isBlank(visit.getPurpose())) {
			return "拜访目的不能为空";
		}
		
		return "";
	}
		
	/**
	 * 删除拜访计划
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
	public Object delete(@PathVariable("id") Long id ,HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "id不能为空");
		}
		
		service.delete(id);
		
		return ResponseUtil.getObject();
	}
	
	/**
	 * 批量删除拜访计划
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "batch", method = RequestMethod.DELETE)
	public Object batchDelete(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");		

		if (idsStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}
		
		String[] idArray = idsStr.split(",");
		
		if (idArray.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}
		
		Page<VisitsVO> visitPage = service.batchDelete(idArray, getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));
				
		return ResponseUtil.getObject(visitPage);
	}
	
	public Date transfromDateFromStr(String dateStr) throws ParseException{
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
		 Date date = sdf.parse(dateStr);
		 return date;
	}
	
}
